package m202405.d22;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/22 17:51
 */
public class Q25 {

    public static void main(String[] args) {
        ListNode root = new ListNode(1);
        root.next = new ListNode(2);
        root.next.next = new ListNode(3);
        root.next.next.next = new ListNode(4);
        root.next.next.next.next = new ListNode(5);
        Q25 q25 = new Q25();
        q25.reverseKGroup(root, 2);
        System.out.println();
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode temp = new ListNode();
        temp.next = head;
        ListNode fast = temp;
        ListNode slow = temp;
        while (true) {
            for (int i = 0; i < k && fast != null; i++) {
                fast = fast.next;
            }
            if (fast == null) {
                break;
            }
            ListNode tailNext = fast.next;
            ListNode headPre = slow.next;
            reverse(slow, k, tailNext);
            slow = headPre;
            fast = slow;
        }
        return temp.next;
    }

    private void reverse(ListNode headPre, int k, ListNode tail) {
        ListNode temp = new ListNode();
        temp.next = tail;
        ListNode p = headPre.next;
        int i = 0;
        while (i < k) {
            ListNode c = p;
            p = p.next;
            c.next = temp.next;
            temp.next = c;
            i++;
        }
        headPre.next = temp.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
